package com.lsh.payment.api.service.exception;


import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.payment.api.model.basevo.BaseResponse;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.Date;

/**
 * Project Name: lsh-payment
 * Author: peter
 * 北京链商电子商务有限公司
 * Desc: 业务异常mapper
 * Package Name:
 * Time: 2018-06-05 下午2:51
 * @author peter
 */
public class SystemExceptionMapper implements ExceptionMapper<Exception> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Response toResponse(Exception ex) {

        logger.error("systemExceptionMapper deal", ex);
        BusinessException bex = null;
        Response.Status status = Response.Status.INTERNAL_SERVER_ERROR;
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setTimestamp(new Date());

        try {
            if (ex instanceof JsonMappingException) {
                bex = ExceptionStatus.E1001001.exception("【数据格式不正确】");
            } else if (ex instanceof NotFoundException) {
                bex = ExceptionStatus.E1001000.exception("【请求url不正确or不存在】 or 【请求方式错误】");
                status = Response.Status.NOT_FOUND;
            }

            String exMsg = ex.getMessage();
            if (exMsg != null && exMsg.contains("DuplicateKeyException")) {
                bex = ExceptionStatus.E1001001.exception("【违反唯一约束】");
            }

            if (bex == null) {
                bex = ExceptionStatus.E1001001.exception();
            }

            baseResponse.setRet(Integer.valueOf(bex.getCode()));
            baseResponse.setMsg(bex.getCode());
        } catch (NumberFormatException e) {
            baseResponse.setRet(1001001);
            baseResponse.setMsg("系统繁忙，请稍后再试");
        }

        return Response.status(status).entity(baseResponse)
                .header("X-Frame-Options", "SAMEORIGIN")
                .type(ContentType.APPLICATION_JSON_UTF_8)
                .build();
    }

}
